package cn.flying.system.service.cm.impl;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.flying.base.common.vo.PageRequest;
import cn.flying.base.common.vo.PageResponse;
import cn.flying.system.common.enums.SeqTypeEnum;
import cn.flying.system.common.vo.UserRelationInfoVo;
import cn.flying.system.domain.cm.CmOrganization;
import cn.flying.system.domain.cm.CmPositionUser;
import cn.flying.system.domain.cm.CmPositionUserExample;
import cn.flying.system.domain.cm.CmUser;
import cn.flying.system.domain.cm.CmUserExample;
import cn.flying.system.domain.cm.CmUserRole;
import cn.flying.system.domain.cm.CmUserRoleExample;
import cn.flying.system.mapper.cm.CmPositionUserMapper;
import cn.flying.system.mapper.cm.CmUserMapper;
import cn.flying.system.mapper.cm.CmUserRoleMapper;
import cn.flying.system.service.cm.CmOrganizationService;
import cn.flying.system.service.cm.CmSeqService;
import cn.flying.system.service.cm.CmUserService;

/**
 * @description: 系统用户信息接口实现类
 * @author: lvyong
 * @date: 2022年05月22日 08:14
 * @version: 1.0
 */
@Service
public class CmUserServiceImpl implements CmUserService {

    @Resource
    private CmUserMapper cmUserMapper;
    @Resource
    private CmPositionUserMapper cmPositionUserMapper;
    @Resource
    private CmUserRoleMapper cmUserRoleMapper;
    @Autowired
    private CmSeqService cmSeqService;
    @Autowired
    private CmOrganizationService cmOrganizationService;

    /**
     * 查询用户列表-分页
     *
     * @param pageRequest
     * @return
     */
    @Override
    public PageResponse<CmUser> getUserPageList(PageRequest<CmUser> pageRequest) {
        Integer pageNum = pageRequest.getPageNum();
        Integer pageSize = pageRequest.getPageSize();
        CmUser user = pageRequest.getParam();
        CmUserExample example = new CmUserExample();
        CmUserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.hasText(user.getUserId())) {
            criteria.andUserIdEqualTo(user.getUserId());
        }
        if (StringUtils.hasText(user.getUsername())) {
            criteria.andUsernameEqualTo(user.getUsername());
        }
        if (StringUtils.hasText(user.getOrgId())) {
            criteria.andOrgIdEqualTo(user.getOrgId());
        }
        PageHelper.offsetPage((pageNum - 1) * pageSize, pageSize);
        Page<CmUser> page = (Page<CmUser>) cmUserMapper.selectByExample(example);
        return new PageResponse(page.getTotal(), pageNum, page.getResult());
    }

    /**
     * 根据主键ID查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public CmUser getUserById(Long id) {
        return cmUserMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据userId称查询
     *
     * @param userId
     * @return
     */
    @Override
    public CmUser findUserByUserId(String userId) {
        CmUserExample userExample = new CmUserExample();
        CmUserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<CmUser> list = cmUserMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据用户名称查询
     *
     * @param username
     * @return
     */
    @Override
    public CmUser findUserByUsername(String username) {
        CmUserExample userExample = new CmUserExample();
        CmUserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<CmUser> list = cmUserMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 保存用户信息
     *
     * @param userRelationInfoVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUser(UserRelationInfoVo userRelationInfoVo) {
        String seq = cmSeqService.getSeq(SeqTypeEnum.USER.name());
        userRelationInfoVo.setUserId(seq);
        userRelationInfoVo.setPassword(seq);
        CmOrganization organization = cmOrganizationService.getOrganizationByOrgCode(userRelationInfoVo.getOrgId());

        CmUser cmUser = new CmUser();
        BeanUtils.copyProperties(userRelationInfoVo, cmUser);
        cmUser.setOrgName(organization.getOrgName());
        //设置默认密码
//        cmUser.setPassword(CryptographyUtil.sha256(cmUser.getUsername(), "Aa123456,.", 1024));
        cmUser.setPassword("");
        cmUserMapper.insertSelective(cmUser);

        List<String> positions = userRelationInfoVo.getPositions();
        CmPositionUser positionUser;
        for (String position : positions) {
            positionUser = new CmPositionUser();
            positionUser.setUserId(seq);
            positionUser.setPostId(position);
            cmPositionUserMapper.insertSelective(positionUser);
        }

        List<String> roles = userRelationInfoVo.getRoles();
        CmUserRole userRole;
        for (String role : roles) {
            userRole = new CmUserRole();
            userRole.setUserId(seq);
            userRole.setRoleId(role);
            cmUserRoleMapper.insertSelective(userRole);
        }
    }

    /**
     * 修改用户信息
     *
     * @param userRelationInfoVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserById(UserRelationInfoVo userRelationInfoVo) {
        CmOrganization organization = cmOrganizationService.getOrganizationByOrgCode(userRelationInfoVo.getOrgId());

        CmUser cmUser = new CmUser();
        BeanUtils.copyProperties(userRelationInfoVo, cmUser);
        cmUser.setOrgName(organization.getOrgName());
        cmUserMapper.updateByPrimaryKeySelective(cmUser);

        List<String> positions = userRelationInfoVo.getPositions();
        if (!CollectionUtils.isEmpty(positions)) {
            //删除用户原来的岗位配置，重新保存
            CmPositionUserExample example = new CmPositionUserExample();
            CmPositionUserExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userRelationInfoVo.getUserId());
            cmPositionUserMapper.deleteByExample(example);

            CmPositionUser positionUser;
            for (String position : positions) {
                positionUser = new CmPositionUser();
                positionUser.setUserId(userRelationInfoVo.getUserId());
                positionUser.setPostId(position);
                cmPositionUserMapper.insertSelective(positionUser);
            }
        }

        List<String> roles = userRelationInfoVo.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            //删除用户原来的角色配置，重新保存
            CmUserRoleExample example1 = new CmUserRoleExample();
            CmUserRoleExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andUserIdEqualTo(userRelationInfoVo.getUserId());
            cmUserRoleMapper.deleteByExample(example1);

            CmUserRole userRole;
            for (String role : roles) {
                userRole = new CmUserRole();
                userRole.setUserId(userRelationInfoVo.getUserId());
                userRole.setRoleId(role);
                cmUserRoleMapper.insertSelective(userRole);
            }
        }
    }

    /**
     * 删除用户
     *
     * @param cmUser
     */
    @Override
    public void deleteUserById(CmUser cmUser) {
//        Result result = new Result(0, "删除成功");
//        if (user.getId() == null) {
//            result = new Result(2, "删除失败");
//            return result;
//        }
//        userMapper.deleteByPrimaryKey(user.getId());
//        return result;
    }

    /**
     * 根据userId删除用户
     *
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteUserByUserId(String userId) {
        CmUserExample userExample = new CmUserExample();
        CmUserExample.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andUserIdEqualTo(userId);
        cmUserMapper.deleteByExample(userExample);

        CmPositionUserExample example = new CmPositionUserExample();
        CmPositionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        cmPositionUserMapper.deleteByExample(example);
    }

    /**
     * 修改最后登录时间
     *
     * @param username
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserLoginTimeByUsername(String username) {
        CmUser user = findUserByUsername(username);
        user.setLastLoginTime(new Date());
        cmUserMapper.updateByPrimaryKeySelective(user);
    }

    //    /**
//     * 检查用户
//     *
//     * @param user
//     * @param request
//     * @throws Exception
//     */
//    @Override
//    public void checkUser(CmUser user, HttpServletRequest request) throws Exception {
//        HttpSession session = request.getSession();
//        CmUser cmUser = this.findUserByUsername(user.getUsername());
//        if (cmUser == null) {
//            throw new BizException("用户名不存在！");
//        }
////        if (!cmUser.getPassword().equals(MD5Util.MD5Encode(user.getPassword(), "utf-8"))) {
////            throw new BizException("用户或密码不正确！");
////        }
//        String token = UUID.randomUUID().toString().replaceAll("-", "");
//        session.setAttribute(Constants.USER_TOKEN, token);
//        session.setAttribute(token, cmUser.getUsername());
//        //session失效时间 1小时
//        session.setMaxInactiveInterval(60 * 60);
//    }
}
